import { NextResponse } from "next/server";
import pageModule from "@/modules/page";
import generateSlugify from "@/utils/generateSlugify";
import {TIP_TAP_DEFAULT} from "@/config/settings";

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const limit = Number(searchParams.get('limit')) || 10;
  const offset = Number(searchParams.get('offset')) || 0;
  const count = await pageModule.count();
  const pages = await pageModule.getAll({ limit, offset });
  return NextResponse.json({ code: 0, count, message: "success", data: pages });
}

export async function PUT(request) {
  const codeMap = {0: '更新成功', 1: '页面不存在', 2: '状态不能为空', 3: '标题不能为空', 4: '更新失败'};
  const {id, slug: originSlug, status, cover, title, description, content : originContent, meta_title, meta_description, sort, template} = await request.json();
  const page = await pageModule.getById(id);
  if (!page) { return NextResponse.json({ code: 1, codeMap, message: "page not found" }); }
  if (status === undefined || status === null || status === '') {return NextResponse.json({ code: 2, codeMap, message: "status is required" }); }
  if (!title) {return NextResponse.json({ code: 3, codeMap, message: "title is required" }); }
  const content = originContent ? JSON.stringify(originContent) : JSON.stringify(TIP_TAP_DEFAULT);
  const slugList = await pageModule.getSlugs();
  const slug = !originSlug ? await generateSlugify(title, slugList) : originSlug;
  const res = await pageModule.update({id, slug, status, cover, title, description, content, meta_title, meta_description, sort, template});
  if (!res) {return NextResponse.json({ code: 4, codeMap, message: "update failed" }); }
  return NextResponse.json({ code: 0, codeMap, message: "success" });
}

export async function POST(request) {
  const codeMap = {0: '创建成功', 1: '状态不能为空', 2: '标题不能为空', 3: '创建失败'};
  const { slug: originSlug, status, cover, title, description, content : originContent, meta_title, meta_description, sort, template: originTemplate } = await request.json();
  if (status === undefined || status === null || status === '') {return NextResponse.json({ code: 1, codeMap, message: "status is required" }); }
  if (!title) {return NextResponse.json({ code: 2, codeMap, message: "title is required" }); }
  const content = originContent ? JSON.stringify(originContent) : JSON.stringify(TIP_TAP_DEFAULT);
  const slug = originSlug;
  const template = !!originTemplate ? originTemplate : 'default';
  const res = await pageModule.create({slug, status, cover, title, description, content, meta_title, meta_description, sort, template});
  if (!res) {return NextResponse.json({ code: 3, codeMap, message: "create failed" }); }
  return NextResponse.json({ code: 0, codeMap, message: "success", data: { id: res } });
}